package bb.lanxing.activity.bluetooth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Html;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;

import org.apache.commons.cli.HelpFormatter;

import bb.lanxing.R;
import bb.lanxing.databinding.ActivityHeartRate01SettingBinding;
import bb.lanxing.devices.utils.XZDeviceHelper;
import bb.lanxing.lib.devices.ble.device.HeartRate01Device;
import bb.lanxing.lib.devices.heartrate01.HeartRate01WarningInfo;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.mvvm.base.BaseDBActivity;
import bb.lanxing.util.ui.InputHelper;
import bb.lanxing.view.BiciAlertDialogBuilder;

public class HeartRate01SettingActivity extends BaseDBActivity<ActivityHeartRate01SettingBinding> {
    final static private String TAG = "HeartRate01SettingActivity";
    ActivityHeartRate01SettingBinding sectionSettingBinding;
    private int[] sections = null;

    public static final int FLAG_MAX = -1;
    public static final int FLAG_MIN = -2;
    HeartRate01WarningInfo warningInfo;

    @Override
    public int getLayoutId() {
        return R.layout.activity_heart_rate01_setting;
    }

    @Override
    public void initView(ActivityHeartRate01SettingBinding binding) {
        sectionSettingBinding = binding;
        setupActionBar(true);
        registerReceiver();
        XZDeviceHelper.getHeartRate01Controller().readHeartRateWaningInfo();
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(HeartRate01Device.ACTION_DEVICE_HEART_RATE_WARNING);
        registerReceiver(broadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
    }

    private void initView() {
        sectionSettingBinding.warningSwitch.setOnCheckedChangeListener((compoundButton, z2) -> {
            sectionSettingBinding.warningValueLayout.setVisibility(z2 ? View.VISIBLE : View.GONE);
            if (z2 && binding.warningSwitchMin.isChecked()) {
                String maxValue = binding.warningValueView.getText().toString();
                String minValue = binding.warningValueViewMin.getText().toString();
                if (Integer.parseInt(maxValue) < Integer.parseInt(minValue)) {
                    binding.warningValueView.setText(String.valueOf(Integer.parseInt(minValue) + 1));
                }
            }
        });
        sectionSettingBinding.warningSwitchMin.setOnCheckedChangeListener((compoundButton, z2) -> {
            sectionSettingBinding.warningValueLayoutMin.setVisibility(z2 ? View.VISIBLE : View.GONE);
            if (z2 && binding.warningSwitch.isChecked()) {
                String maxValue = binding.warningValueView.getText().toString();
                String minValue = binding.warningValueViewMin.getText().toString();
                if (Integer.parseInt(maxValue) < Integer.parseInt(minValue)) {
                    binding.warningValueViewMin.setText(String.valueOf(Integer.parseInt(maxValue) - 1));
                }
            }
        });


        sectionSettingBinding.learnHeartRateZone.setOnClickListener(this::showZoneInfo);
        sectionSettingBinding.heartRateZ1.setOnClickListener(v -> showEditDialog(0, String.valueOf(sections[0])));
        sectionSettingBinding.heartRateZ2.setOnClickListener(v -> showEditDialog(1, String.valueOf(sections[1])));
        sectionSettingBinding.heartRateZ3.setOnClickListener(v -> showEditDialog(2, String.valueOf(sections[2])));
        sectionSettingBinding.heartRateZ4.setOnClickListener(v -> showEditDialog(3, String.valueOf(sections[3])));
        sectionSettingBinding.heartRateZ5.setOnClickListener(v -> showEditDialog(4, String.valueOf(sections[4])));
        sectionSettingBinding.heartRateMax.setOnClickListener(v -> showEditDialog(5, String.valueOf(sections[5])));
        sectionSettingBinding.warningUnitView.setOnClickListener(v -> setupHeartWarning(v, FLAG_MAX));
        sectionSettingBinding.warningUnitViewMin.setOnClickListener(v -> setupHeartWarning(v, FLAG_MIN));
        updateSectionView();
    }


    public void updateSectionView() {
        for (int length = sections.length - 1; length >= 0; length--) {
            int[] iArr2 = sections;
            int i = iArr2[length];
            if (length == iArr2.length - 1) {
                sectionSettingBinding.heartRateMax.setText(getString(R.string.str_fm_unit_bpm, String.valueOf(i)));
            } else {
                String string = getString(R.string.mine_section_setting_hr_value, String.valueOf(iArr2[length + 1]), String.valueOf(sections[length]));
                int indexOf = string.indexOf(HelpFormatter.DEFAULT_OPT_PREFIX);
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(ContextCompat.getColor(this, R.color.grey_999999));
                ForegroundColorSpan foregroundColorSpan2 = new ForegroundColorSpan(ContextCompat.getColor(this, R.color.grey_666666));
                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(string);
                spannableStringBuilder.setSpan(foregroundColorSpan, 0, indexOf, 33);
                spannableStringBuilder.setSpan(foregroundColorSpan2, indexOf + 1, string.length(), 33);
                switch (length) {
                    case 0 -> sectionSettingBinding.heartRateZ1.setText(spannableStringBuilder);
                    case 1 -> sectionSettingBinding.heartRateZ2.setText(spannableStringBuilder);
                    case 2 -> sectionSettingBinding.heartRateZ3.setText(spannableStringBuilder);
                    case 3 -> sectionSettingBinding.heartRateZ4.setText(spannableStringBuilder);
                    case 4 -> sectionSettingBinding.heartRateZ5.setText(spannableStringBuilder);
                    default -> {
                    }
                }
            }
        }
    }

    private void initData() {
//        String hearrRateSegment = SharedManager.getInstance().getHeartRate01SectionWithMP();
//        int[] parse = SectionParseUtil.parse(hearrRateSegment, 6);
//        sections = parse;
//        if (parse == null || parse.length == 0) {
//            if (sections == null) {
//                sections = new int[]{98, 117, 137, 156, 176, 196};
//            }
//        }
    }

    public void showEditDialog(final int i, final String str) {
        View inflate = LayoutInflater.from(this).inflate(R.layout.edittext_view, (ViewGroup) null);
        final EditText editText = inflate.findViewById(R.id.editText);
        editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS | InputType.TYPE_CLASS_NUMBER);
        editText.setMaxLines(1);
        if (TextUtils.isEmpty(str)) {
            editText.setHint(R.string.dialog_hint_input);
        } else {
            editText.setText(str);
        }

        AlertDialog.Builder mSetNegativeButton = new BiciAlertDialogBuilder(this).setView(inflate).setPositiveButton(R.string.dialog_btn_ok, (dialogInterface, i2) -> {
            String obj = editText.getText().toString();
            if (TextUtils.isEmpty(obj) || obj.equals(str)) {
                dialogInterface.cancel();
            } else {
                int parseInt = Integer.parseInt(obj);
                if (i == FLAG_MAX) {
                    String minValue = binding.warningValueViewMin.getText().toString();
                    if (parseInt >= 250) {
                        binding.warningValueView.setText(String.valueOf(249));
                    } else if (binding.warningSwitchMin.isChecked() && !TextUtils.isEmpty(minValue) && parseInt < Integer.parseInt(minValue)) {
                        binding.warningValueView.setText(String.valueOf(Integer.parseInt(minValue) + 1));
                    } else {
                        sectionSettingBinding.warningValueView.setText(String.valueOf(parseInt));
                    }
                } else if (i == FLAG_MIN) {
                    String maxValue = binding.warningValueView.getText().toString();
                    if (binding.warningSwitch.isChecked() && !TextUtils.isEmpty(maxValue) && parseInt > Integer.parseInt(maxValue)) {
                        binding.warningValueViewMin.setText(String.valueOf(Integer.parseInt(maxValue) - 1));
                    } else {
                        sectionSettingBinding.warningValueViewMin.setText(String.valueOf(parseInt));
                    }
                } else {
                    updateSections(i, Math.abs(parseInt));
                    String makeSectionString = makeSectionString(sections);
                    updateSectionView();
                }
            }
            InputHelper.hideSoftInput(editText);
        }).setNegativeButton(R.string.dialog_btn_cancel, (dialogInterface, i2) -> InputHelper.hideSoftInput(editText));
        mSetNegativeButton.setTitle(R.string.mine_section_setting_dialog_input);
        mSetNegativeButton.show();
        InputHelper.showSoftInput(editText);
    }

    public void updateSections(int index, int section) {
        int[] iArr = sections;
        if (iArr == null) {
            return;
        }
        int i = 1;
        if (iArr.length - 1 == index) {
            int length = iArr.length - 1;
            int i2 = 10;
            while (length > 0) {
                sections[length] = (int) (section * (i2 / 10.0f));
                length--;
                i2--;
            }
        }
        sections[index] = section;
        while (true) {
            int[] iArr2 = sections;
            if (i >= iArr2.length) {
                return;
            }
            restrictSectionValue(i, iArr2[i]);
            i++;
        }
    }

    private void restrictSectionValue(int index, int section) {
        Log.v(TAG, "updateSections, index = " + index + ", section = " + section);
        int[] iArr = sections;
        int i = index == iArr.length + (-1) ? 250 : iArr[index + 1];
        int i2 = iArr[index - 1];
        if (section >= i) {
            section = i - 1;
        } else if (section <= i2) {
            section = i2 + 1;
        }
        iArr[index] = section;
    }

    public String makeSectionString(int[] sections) {
        String str = "";
        for (int i = 0; i < sections.length; i++) {
            str = str + sections[i];
            if (i < sections.length - 1) {
                str = str + ";";
            }
        }
        Log.v(TAG, "makeSectionString, jsonStr = " + str);
        return str;
    }

    public void showZoneInfo(View view) {
        Spanned fromHtml;
        fromHtml = Html.fromHtml(getString(R.string.mine_section_setting_hr_about_zone), 0);
        new BiciAlertDialogBuilder(HeartRate01SettingActivity.this).setMessage(fromHtml).show();
    }

    public void setupHeartWarning(View view, int flag) {
        int heartRateWarningValue = 0;
        if (flag == FLAG_MAX) {
            if (!TextUtils.isEmpty(binding.warningValueView.getText().toString())) {
                heartRateWarningValue = Integer.parseInt(binding.warningValueView.getText().toString());
            }
        } else {
            if (!TextUtils.isEmpty(binding.warningValueViewMin.getText().toString())) {
                heartRateWarningValue = Integer.parseInt(binding.warningValueViewMin.getText().toString());
            }
        }
        showEditDialog(flag, String.valueOf(heartRateWarningValue));
    }

    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (HeartRate01Device.ACTION_DEVICE_HEART_RATE_WARNING.endsWith(intent.getAction())) {
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    warningInfo = (HeartRate01WarningInfo) bundle.getSerializable(HeartRate01Device.EXTRA_HEART_RATE_WARING);
                    setUIData();
                }
            }
        }
    };

    private void setUIData() {
        if (warningInfo != null) {
            binding.warningSwitch.setChecked(warningInfo.highWarning == 1);
            sectionSettingBinding.warningValueLayout.setVisibility(binding.warningSwitch.isChecked() ? View.VISIBLE : View.GONE);
            if (warningInfo.highWarningValue == 0) {
                binding.warningValueView.setText(String.valueOf(170));
            } else {
                binding.warningValueView.setText(String.valueOf(warningInfo.highWarningValue));
            }

            binding.warningSwitchMin.setChecked(warningInfo.lowWarning == 1);
            sectionSettingBinding.warningValueLayoutMin.setVisibility(binding.warningSwitchMin.isChecked() ? View.VISIBLE : View.GONE);
            binding.warningValueViewMin.setText(String.valueOf(warningInfo.lowWarningValue));
            sections = new int[]{warningInfo.zoomLevel1, warningInfo.zoomLevel2, warningInfo.zoomLevel3, warningInfo.zoomLevel4, warningInfo.zoomLevel5, warningInfo.zoomLevel6};
            initView();
        }
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(broadcastReceiver);
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (warningInfo != null) {
            warningInfo.highWarning = (byte) (binding.warningSwitch.isChecked() ? 1 : 0);
            warningInfo.lowWarning = (byte) (binding.warningSwitchMin.isChecked() ? 1 : 0);
            warningInfo.highWarningValue = Integer.parseInt(binding.warningValueView.getText().toString());
            warningInfo.lowWarningValue = Integer.parseInt(binding.warningValueViewMin.getText().toString());

            warningInfo.zoomLevel1 = sections[0];
            warningInfo.zoomLevel2 = sections[1];
            warningInfo.zoomLevel3 = sections[2];
            warningInfo.zoomLevel4 = sections[3];
            warningInfo.zoomLevel5 = sections[4];
            warningInfo.zoomLevel6 = sections[5];
            if (!isAscending()) {
                toast(R.string.toast_save_failure);
                return;
            }
            XZDeviceHelper.getHeartRate01Controller().writeHeartRateWaningInfo(warningInfo);

        }
    }

    public boolean isAscending() {
        for (int i = 0; i < sections.length - 1; i++) {
            if (sections[i] > sections[i + 1]) {
                return false;
            }
        }
        return true;
    }
}
